package cn.hejiang.mamis.core.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerUtils;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;

@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class CacheConfig {
	@Bean
	public CacheManager cacheManager(net.sf.ehcache.CacheManager cacheManager) {
		return new EhCacheCacheManager(cacheManager) {
			@Override
			public Cache getCache(String name) {
				Cache cache = super.getCache(name);
				if (cache != null) {
					return cache;
				}

				getCacheManager().addCacheIfAbsent(name);
				return super.getCache(name);
			}
		};
	}

	@Bean
	public net.sf.ehcache.CacheManager ehCacheCacheManager(CacheProperties cacheProperties) {
		Resource location = cacheProperties.resolveConfigLocation(cacheProperties.getEhcache().getConfig());
		if (location != null) {
			return EhCacheManagerUtils.buildCacheManager(location);
		}
		return EhCacheManagerUtils.buildCacheManager();
	}

	@Bean
	public KeyGenerator cacheKeyGenerator() {
		return (target, method, params) -> {
			StringBuilder sb = new StringBuilder();
			sb.append(target.getClass().getName()).append(":").append(method.getName());
			sb.append(":").append(DigestUtil.md5Hex(JSONUtil.toJsonStr(params)));
			return sb.toString();
		};
	}
}
